package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"perfect-admin/global"
	"perfect-admin/global/response"
	"perfect-admin/model"
	"perfect-admin/model/request"
	"perfect-admin/service"
	"perfect-admin/utils"
	"strconv"
)

func GetApiTree(c *gin.Context) {
	role_id := c.Query("role_id")
	if role_id == "" {
		response.Response(c, 201, "参数接收有误", nil)
		return
	}
	AuthorityIdVerifyErr := utils.Verify(request.CasbinInReceive{RoleId:role_id}, utils.CustomizeMap["AuthorityIdVerify"])
	if AuthorityIdVerifyErr != nil {
		response.Response(c, 202, AuthorityIdVerifyErr.Error(), nil)
		return
	}
	apidefkeys := service.GetPolicyNodeByRoleId(role_id)
	api_list := service.GetApiTree()
	response.Response(c, http.StatusOK, "获取Api树成功", map[string]interface{}{
		"api_list": api_list,
		"ApidefKeys": apidefkeys,
	})
	return
}

func GetApiList(c *gin.Context) {
	var queryInfo request.QueryInfo
	if err := c.ShouldBind(&queryInfo); err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	apis, total, err := service.GetApiList(queryInfo)
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取Api列表成功", "data": map[string]interface{}{
			"apis": apis,
			"total": total,
		}})
	}
	return
}

func GetApiGroup(c *gin.Context) {
	api_group_list, err := service.GetApiGroup()
	if err != nil {
		response.Response(c, 201, err.Error(), nil)
	} else {
		response.Response(c, http.StatusOK, "获取Api列表成功", api_group_list)
	}
	return
}

func AddApi(c *gin.Context) {
	var api model.SysApi
	err := c.ShouldBindJSON(&api)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	err = service.AddApi(api)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "添加Api成功", "data": nil})
	}
	return
}


func UpdateApi(c *gin.Context) {
	var api model.SysApi
	if err := c.ShouldBindJSON(&api); err != nil {
		global.LOG.Debug("获取参数失败", err)
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.UpdateApiInfo(api)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "修改Api成功", "data": nil})
	}
	return
}

func DeleteApi(c *gin.Context) {
	api_id, ok := c.GetQuery("id")
	apiId, err := strconv.Atoi(api_id)
	if !ok || err != nil {
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err = service.DeleteApi(uint(apiId))
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "删除Api成功", "data": nil})
	}
	return
}

